package com.zzsy.shoppingpro.http;


import android.annotation.SuppressLint;
import android.util.Log;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.zzsy.shoppingpro.BuildConfig;
import com.zzsy.shoppingpro.app.Config;
import com.zzsy.shoppingpro.app.application;
import com.zzsy.shoppingpro.utils.ApkInfoUtil;
import com.zzsy.shoppingpro.utils.SPHelper;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 添加配置的重写方法
 * Created by Administrator on 2016/09/14.
 */
public class RetrofitHelper {

    private static OkHttpClient okHttpClient = null;

    public static <T> T create(Class<T> clazz) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.BASE_URL)
                //增加返回值为Gson的支持(以实体类返回)
                .addConverterFactory(GsonConverterFactory.create())
                //增加返回值为Observable<T>的支持
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //这里指定使用
                .client(okHttpClient)
                .build();
        return retrofit.create(clazz);//这里采用的是Java的动态代理模式
    }

    public static <T> T create(Class<T> clazz,String url) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                //增加返回值为Gson的支持(以实体类返回)
                .addConverterFactory(GsonConverterFactory.create())
                //增加返回值为Observable<T>的支持
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //这里指定使用
                .client(okHttpClient)
                .build();
        return retrofit.create(clazz);//这里采用的是Java的动态代理模式
    }




    static {
        final String jwt = (String)(SPHelper.getSimpleParam(application.getApp(), "jwt", ""));
        final String versionName = ApkInfoUtil.getVersionName(application.getApp());
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //配置拦截器
        Interceptor interceptor = new Interceptor() {
            @SuppressLint("LongLogTag")
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                HttpUrl.Builder urlBuilder = originalRequest.url().newBuilder();
                HttpUrl url = urlBuilder.build();
                //统一添加header
                Request request = originalRequest.newBuilder()
                        .addHeader("version", versionName)
                        .addHeader("type", String.valueOf(Config.ANDROID_ORDER))
                        .addHeader("jwt", jwt != null && !jwt.isEmpty() ? jwt : "")
                        .url(url)
                        .build();
                if (BuildConfig.DEBUG) {
                    //打印POST请求
                    StringBuilder paramsBuilder = new StringBuilder();
                    if (originalRequest.body() instanceof FormBody) {
                        FormBody newBody = (FormBody) originalRequest.body();
                        for (int i = 0, j = newBody.size(); i < j; i++) {
                            paramsBuilder.append("&");
                            paramsBuilder.append(newBody.name(i));
                            paramsBuilder.append("=");
                            paramsBuilder.append(newBody.value(i));
                        }
                    }
                    Log.e(Config.TAG, request.headers() + ";" + url.url().toString() + paramsBuilder.toString());
                }
                return chain.proceed(request);
            }
        };
        SSLContext sslContext = SSLContextUtil.getDefaultSLLContext();
        if (sslContext != null){
            builder.sslSocketFactory(sslContext.getSocketFactory());
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
        okHttpClient =new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 直接转换为字符串
     * @param clazz Class
     * @param <T> API
     * @return T
     */
    public static <T> T createString(Class<T> clazz) {
        return createString(clazz, Config.BASE_URL);
    }

    /**
     * 直接转换为字符串(指定服务器地址)
     * @param clazz Class
     * @param url String
     * @param <T> API
     * @return T
     */
    public static <T> T createString(Class<T> clazz, String url) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                //这里指定使用
                .callFactory(okHttpClient)
                //增加返回值为Observable<T>的支持
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(StringConverterFactory.create())
                .build();
        return retrofit.create(clazz);
    }
}
